import Layout from "@/layout";
import { Logger } from "@/utils/log";
import NotFound from "@/views/notFound";
import {
  createRootRoute,
  RouterProvider,
  createRouter,
  AnyRoute,
  createRoute,
} from "@tanstack/react-router";
import { ComponentType, lazy, Suspense } from "react";

const rootRoute = createRootRoute({
  component: Layout,
  notFoundComponent: NotFound,
});

const views = import.meta.glob<{ default: ComponentType }>(
  "@/views/**/index.tsx"
);

function LazyImportComponent(props: { lazyChildren: ComponentType }) {
  return (
    <Suspense>
      <props.lazyChildren />
    </Suspense>
  );
}
const lazyLoader = (
  componentImport: () => Promise<{ default: ComponentType }>
) =>
  lazy(
    () =>
      new Promise<{ default: ComponentType }>((resolve) => {
        componentImport()
          .then((d) => {
            resolve(d);
          })
          .catch((e) => {
            // 上报错误日志
            Logger.error("lazyLoader:", e);
            resolve({ default: NotFound });
          });
      })
  );

function getAutoRoutes(parentRoute: AnyRoute) {
  const groupRouteMap: Record<string, AnyRoute> = {};
  const groupRouteChildrenMap: Record<string, AnyRoute[]> = {};

  Object.entries(views).forEach(([filePath, lazyComp]) => {
    // 调整正则表达式以支持两种目录结构
    const match = filePath.match(
      /\/src\/views\/([^/]+)(?:\/([^/]+))?\/index\.tsx$/
    );
    if (!match) return;
    const group = match[1];
    const subPath = match[2]; // 可能为 undefined
    if (!group) return;
    // 创建或获取父路由
    if (!groupRouteMap[group]) {
      groupRouteMap[group] = createRoute({
        getParentRoute: () => parentRoute,
        path: group === "home" ? "/" : `/${group}`,
        notFoundComponent: NotFound,
        // 如果当前文件没有子路径，直接设置组件
        component: !subPath
          ? () => <LazyImportComponent lazyChildren={lazyLoader(lazyComp)} />
          : undefined,
      });
      groupRouteChildrenMap[group] = [];
    }
    // 处理子路由
    if (subPath) {
      groupRouteChildrenMap[group].push(
        createRoute({
          getParentRoute: () => groupRouteMap[group],
          path: subPath,
          component: () => (
            <LazyImportComponent lazyChildren={lazyLoader(lazyComp)} />
          ),
        })
      );
    } else {
      // 确保父路由组件设置（处理可能先处理子路由的情况）
      if (!groupRouteMap[group].options.component) {
        groupRouteMap[group].options.component = () => (
          <LazyImportComponent lazyChildren={lazyLoader(lazyComp)} />
        );
      }
    }
  });

  return Object.entries(groupRouteMap).map(([key, route]) =>
    route.addChildren(groupRouteChildrenMap[key])
  );
}

export default function Routers() {
  const routeTree = rootRoute.addChildren(getAutoRoutes(rootRoute));
  const router = createRouter({
    routeTree,
    defaultPreload: "intent",
    defaultOnCatch(error, errorInfo) {
      Logger.error("createRouterError:", error, errorInfo);
    },
  });
  return <RouterProvider router={router} />;
}
